import { _decorator, Button, instantiate, Label, Node } from 'cc';
import EventExt from 'db://cocos-ext/base/EventExt';
import { EVENT_KEY_CHANGE_LANGUAGE } from 'db://cocos-ext/base/EventType';
import MutiLang from 'db://cocos-ext/base/MutiLang';
import { games, yy } from 'yycore';

import { YYPopup } from './YYPopup';

const { ccclass, property } = _decorator;

@ccclass('UILanguage')
export class UILanguage extends YYPopup {

    protected uiType = games.ui.UIType.User3;

    // item
    @property(Node)
    private readonly item: Node = null;

    // content
    @property(Node)
    private readonly content: Node = null;


    start() {
        this.updateUIList();
    }

    // 更新当前语言列表
    private updateUIList() {
        if (!this.item || !this.content)
            return;
        if (this.content.children.length > 0) {
            this.content.children.forEach(n => n.active = false);
        }
        const list = MutiLang.uiLangList;
        if (list.length == 0)
            return;

        const obj: { [language: string]: string } = {
            en: 'English',
            zh: '简体中文',
            zhf: '繁體中文',
            th: 'ไทย',
            vi: 'Tiếng Việt',
            hi: 'हिंदी',
            id: 'bahasa Indonesia',
            my: 'မြန်မာ',
            jp: '日本語',
            kr: '한국어',
            ms: "Malay",
            pt: "Português",
            es: "Italiano",
        };
        for (let i = 0; i < list.length; i++) {
            const key = list[i];
            const node = this.content.children[i] || instantiate(this.item);
            if (!node) continue;
            node.name = key;
            node.active = true;
            node.getChildByName("Label")!.getComponent(Label)!.string = obj[key] || key;
            node.getChildByName("tick")!.active = yy.sys.curLanguage == key;
            node.on(Button.EventType.CLICK, () => this.onBtnClickLanguage(key), this);
            if (!node.parent)
                this.content.addChild(node);
        }
    }

    private onBtnClickLanguage(key: string) {
        yy.sys.setCurrentLanguage(key);
        this.content.children.forEach(node => node.getChildByName("tick")!.active = node.name == key);
        EventExt.emit(EVENT_KEY_CHANGE_LANGUAGE, key);
    }

}

